﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using tunnel_class;
using System.Collections;
using System.Threading;

namespace Copy_Last_Tunnel
{
    public partial class Mfrm : Form
    {
        DataBase m_db;
        int curprj;//储存当前项目的prjid
        int curno;//储存当前项目的期数
        GeoCom geocom;
        public Mfrm()
        {
            InitializeComponent();
            DataBase db = null;
            treeView1.Nodes[0].Expand();
            if (DataBase.ConnectToDataBase("tunnel15.sdf", ref db))
            {
                m_db = db;
            }
            if (!m_db.IsTableInDataBase("tunelprojects"))
            {
                ArrayList list = new ArrayList();
                DataField fild = fild = new DataField("name", "nvarchar(50)", "not null");
                list.Add(fild);
                fild = new DataField("id", "integer", "not null");
                list.Add(fild);
                fild = new DataField("no", "integer", "not null");
                list.Add(fild);
                bool sucess = m_db.CreateNewTable("tunelprojects", list);
            }
            if (!m_db.IsTableInDataBase("record"))
            {
                ArrayList list = new ArrayList();
                DataField fild = fild = new DataField("prjid", "integer", "not null");
                list.Add(fild);
                fild = new DataField("name", "nvarchar(50)", "not null");
                list.Add(fild);
                fild = new DataField("point", "nvarchar(50)", "not null");
                list.Add(fild);
                fild = new DataField("x", "float", "not null");
                list.Add(fild);
                fild = new DataField("y", "float", "not null");
                list.Add(fild);
                fild = new DataField("h", "float", "not null");
                list.Add(fild);
                fild = new DataField("no", "float", "not null");
                list.Add(fild);
                bool sucess = m_db.CreateNewTable("record", list);
            }

            if (!m_db.IsTableInDataBase("config"))
            {
                ArrayList list = new ArrayList();
                DataField fild = fild = new DataField("prjid", "integer", "not null");
                list.Add(fild);
                fild = new DataField("name", "nvarchar(50)", "not null");
                list.Add(fild);
                fild = new DataField("cx", "float", "not null");
                list.Add(fild);
                fild = new DataField("cy", "float", "not null");
                list.Add(fild);
                fild = new DataField("H", "float", "not null");
                list.Add(fild);
                fild = new DataField("r", "float", "not null");
                list.Add(fild);
                bool sucess = m_db.CreateNewTable("config", list);
            }

            if (!m_db.IsTableInDataBase("result"))
            {
                ArrayList list = new ArrayList();
                DataField fild = fild = new DataField("prjid", "integer", "not null");
                list.Add(fild);
                fild = new DataField("name", "nvarchar(50)", "not null");
                list.Add(fild);
                fild = new DataField("point", "nvarchar(50)", "not null");
                list.Add(fild);
                fild = new DataField("val", "float", "not null");
                list.Add(fild);
                fild = new DataField("no", "float", "not null");
                list.Add(fild);
                bool sucess = m_db.CreateNewTable("result", list);
            }
            load_prjs();
        }

        //加载工程选项
        public void load_prjs()
        {
            string sql = "select [name] from [tunelprojects]";
            DataTable dt;
            try
            {
                 dt = m_db.GetDataSet(sql).Tables[0];
            }
            catch
            {
                return;
            }
            treeView1.Nodes[0].Nodes.Clear();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                treeView1.Nodes[0].Nodes.Add(dt.Rows[i]["name"].ToString());

            }
        }

        //新建工程
        private void btnaddprj_Click(object sender, EventArgs e)
        {
            string txt = txtprjname.Text;
            if (txt.Equals(string.Empty))
            {
                MessageBox.Show("工程名不能为空");
                return;
            }
            string sql = "select max(id) from [tunelprojects]";
            DataTable dt = m_db.GetDataSet(sql).Tables[0]; 
            int prjid = 0;
            if (dt == null || dt.Rows.Count == 0)
            {
                prjid = 1;
            }
            else
            {
                string ss = dt.Rows[0][0].ToString();
                try
                {
                    prjid = Convert.ToInt32(dt.Rows[0][0]) + 1;
                }
                catch
                {
                    prjid = 1;
                }
            }
            sql = "Insert into [tunelprojects] values('" + txt + "'," + prjid + ",-1)";
            m_db.ExecuteSQL(sql);
            load_prjs();
        }
        //工程选择后的事件
        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node.Parent == null)
            {
                prjlabel.Text = "当前工程为:";
                return;
            }
            string prj = e.Node.Text;
            prjlabel.Text = "当前工程为:" + prj;
            string sql = "select [id],[no] from [tunelprojects] where [name]='" + prj + "'";
            DataTable dt = m_db.GetDataSet(sql).Tables[0];
            curprj = Convert.ToInt32(dt.Rows[0][0]);
            curno = Convert.ToInt32(dt.Rows[0][1]);
            load_no();
        }


        void load_no()
        {
            if (curno < 0)
            {
                note.Visible = true;
            }
            else
            {
                note.Visible = false;
            }
            int i = 1;
            com_no.Items.Clear();
            com_no.Items.Add(curno);
            while ((curno - i) >= 0 && i < 4)
            {
                com_no.Items.Add(curno - i);
                i++;
            }
            load_points();
        }
        //把要测的点载入listview中去
        void load_points()
        {
            if (curprj == 0)
            {
                listpts.Items.Clear();
                return;
            }
            listpts.Items.Clear();
            string sql = "select [name] from [record] where [prjid]=" + curprj + " and [no]=0"
                + " group by [name] order by [name]";
            DataTable dt = m_db.GetDataSet(sql).Tables[0];
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string name = dt.Rows[i]["name"].ToString();
                sql = "select [name] from [record] where [prjid]=" + curprj + " and [no]="
                    + curno
                + " and [name]='" + name + "'";
                DataTable table = m_db.GetDataSet(sql).Tables[0];
                if (table.Rows.Count == 0)
                {
                    listpts.Items.Add(name);
                }
                else
                {
                    listpts.Items.Add(name + "(已测)");
                }
            }
        }
        void load_reuslt_pts()
        {
            if (curprj == 0)
            {
                list_result.Items.Clear();
                return;
            }
            list_result.Items.Clear();
            string sql = "select [name] from [record] where [prjid]=" + curprj + " and [no]="+curno
                + " group by [name] order by [name]";
            DataTable dt = m_db.GetDataSet(sql).Tables[0];
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string name = dt.Rows[i]["name"].ToString();
                list_result.Items.Add(name);
            }
            dataGrid1.DataSource = null;
        }
  
        //no选择之后的事件
        private void com_no_SelectedIndexChanged(object sender, EventArgs e)
        {
            object ob = com_no.Items[com_no.SelectedIndex];
            curno = Convert.ToInt32(ob);


            if (curno == 0)
            {
                tabcontrol.SelectedIndex = 2;
                tabcontrol.Refresh();
         
            }
            if (curno > 0)
            {
                tabcontrol.SelectedIndex = 3;
                tabcontrol.Refresh();
                //
            }
            load_points();
            load_reuslt_pts();
        }
        //增加一期数据
        private void button1_Click(object sender, EventArgs e)
        {
            curno = curno + 1;
            string sql = "update [tunelprojects] set [no]="
                + curno + " where [id]=" + curprj;
            m_db.ExecuteSQL(sql);
            load_no();
            MessageBox.Show("新增期数成功!");
        }
        #region 连接设备
        private void bConnect_Click(object sender, EventArgs e)
        {
            if (Combox.Text.Equals(string.Empty))
            {
                MessageBox.Show("请选择COM口");
                return;
            }
            try
            {
                string com = Combox.Text;
                if (geocom != null && geocom.port.IsOpen)
                {
                    geocom.port.Close();
                }
                geocom = new GeoCom(com);
                bConnect.Enabled = false;
                bDisConnect.Enabled = true;
                try
                {
                    geocom.Set_Laser("1");
                    geocom.Set_Measure_Mode("RL");
                }
                catch (Exception ab)
                {
                    bConnect.Enabled = true;
                    bDisConnect.Enabled = false;
                    MessageBox.Show(ab.Message);
                }
            }
            catch (Exception a)
            {
                bConnect.Enabled = true;
                bDisConnect.Enabled = false;
                MessageBox.Show(a.Message);
            }
        }
        private void bDisConnect_Click(object sender, EventArgs e)
        {
            try
            {
                geocom.port.Close();
                bConnect.Enabled = true;
                bDisConnect.Enabled = false;
            }
            catch (Exception a)
            {
                MessageBox.Show(a.Message);
            }
        }
        #endregion
        #region 测量


        //点号变化就改变测点号
        private void listpts_SelectedIndexChanged(object sender, EventArgs e)
        {
            int index = listpts.SelectedIndex;
            if (index < 0)
            {
                lbpoint.Text="未选择点";
                return;
            }

            lbpoint.Text = listpts.Items[index].ToString().Replace("(已测)", "");
            txtheight.Text = "0.000";

        }
        private void btnEdit_Click(object sender, EventArgs e)
        {
            int index = listpts.SelectedIndex;
            if (index == -1) return;
            string Oldname = listpts.Items[index].ToString().Replace("(已测)", "");
            string Newname = lbpoint.Text;
            string sql  = "update [record] set [name]='"+Newname+"' where [name]='"
                + Oldname + "' and [prjid]=" + curprj;
            m_db.ExecuteSQL(sql);
            sql = "update [config] set [name]='" + Newname + "' where [name]='"
                + Oldname + "' and [prjid]=" + curprj;
            m_db.ExecuteSQL(sql);
            sql = "update [result] set [name]='" + Newname + "' where [name]='"
                + Oldname + "' and [prjid]=" + curprj;
            m_db.ExecuteSQL(sql);
            listpts.Items[index] = listpts.Items[index].ToString().Replace(Oldname, Newname);
            MessageBox.Show("修改成功!");
            
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            int index = listpts.SelectedIndex; 
            if (index == -1) return;
            if (MessageBox.Show("是否删除?", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question
                ,MessageBoxDefaultButton.Button1)
                == DialogResult.Yes)
            {
                string name = listpts.Items[index].ToString().Replace("(已测)", "");
                string sql = "delete from [record] where [name]='" + name + "' and [prjid]=" + curprj;
                m_db.ExecuteSQL(sql);
                sql = "delete from [config] where [name]='" + name + "' and [prjid]=" + curprj;
                m_db.ExecuteSQL(sql);
                sql = "delete from [result] where [name]='" + name + "' and [prjid]=" + curprj;
                m_db.ExecuteSQL(sql);
                listpts.Items.RemoveAt(index);
            }
        }
        //获取仪器高
        private void btn_get_height_Click(object sender, EventArgs e)
        {
            try
            {
                if (geocom == null)
                {
                    MessageBox.Show("未连接仪器,请先连接!");
                    return;
                }
                string str = geocom.Measure_Distance_Angle();
                if (!str.Equals("0"))
                {
                    string[] v = str.Split(',');
                    double hv = Convert.ToDouble(v[1]);
                    if (hv > 3.1415926)
                    {
                        MessageBox.Show("请在盘左\r\n测量仪器高");
                        return;
                    }
                    SectionPoint pptt = new SectionPoint("", v[1], v[2]);
                    pptt.CalculateCoor(new TSPCoor(0, 0));
                    txtheight.Text = Math.Round(-pptt.Coor.Coor_V, 4).ToString();
                  
                }
                else
                {
                    MessageBox.Show("添加失败");
                }
            }
            catch
            {
                MessageBox.Show("失败");
            }
        }
        //设hz=0
        private void btnsethz_Click(object sender, EventArgs e)
        {
            if (geocom == null)
            {
                MessageBox.Show("未连接仪器,请先连接!");
                return;
            }
            string result = geocom.Get_Face();
            if (result.Equals("-1"))
            {
                MessageBox.Show("请在正镜下设置水平角");
                return;
            }
            else if (result.Equals("0"))
            {
                MessageBox.Show("出错!");
                return;
            }

            if (geocom.Set_Orientaion().Equals("1"))
            {
                MessageBox.Show("水平角已设置!");
            }
            else
            {
                MessageBox.Show("水平角设置失败");
            }

        }
        private void btnclear_Click(object sender, EventArgs e)
        {
            txtdata.Text = "";
        }
        //开始测量
        private void btnsurvey_Click(object sender, EventArgs e)
        {
            if (txtheight.Text == string.Empty)
            {
                MessageBox.Show("仪器高?");
                return;
            }
            if (geocom == null)
            {
                MessageBox.Show("蓝牙?");
                return;
            }
            if (listpts.SelectedIndex == -1)
            {
                MessageBox.Show("请选择观测点?");
                return;
            }
            if (curno == 0)
            {
                MessageBox.Show("期数不能为0");
                return;
            }
            txtdata.Text = "";
            parase("开始观测:");
            string sql = "select * from [record] where [prjid]="
               + curprj + " and [name]='" + lbpoint.Text + "' and [no]=0 order by [point]";
            DataTable dt = m_db.GetDataSet(sql).Tables[0];
            //double old_instr_H = Convert.ToDouble(dt.Rows[0]["H"]);
            double new_instr_H = Convert.ToDouble(txtheight.Text);

            //double dv = new_instr_H - old_instr_H;
            tunnelSection section = new tunnelSection();
            section.ButtomCenter = new TSPCoor(new_instr_H, 0);
            section.SectNo = lbpoint.Text;
            section.instr_height = new_instr_H;
            pts = new TunnelSectionPoints();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                SectionPoint point = new SectionPoint();
                point.Name = dt.Rows[i]["point"].ToString();
                point.Coor.Coor_H = Convert.ToDouble(dt.Rows[i]["x"]);
                point.Coor.Coor_V = Convert.ToDouble(dt.Rows[i]["y"]);
                pts.Points.Add(point);
            }
            section.SectPnts = pts;
            section.CalButtomCenter2();
            pts = section.SectPnts;
            sql = "delete from [record] where [prjid]=" + curprj + " and [name]='" + section.SectNo +
                "' and [no]=" + curno;
            m_db.ExecuteSQL(sql);
            sql = "delete from [result] where [prjid]=" + curprj + " and [name]='" + section.SectNo +
             "' and [no]=" + curno;
            for (int i = 0; i < pts.Points.Count; i++)
            {
                parase("开始观测第" + (i + 1).ToString() + "点\r\n");
                double hz = 0;
                double hv = pts.Points[i].Hv;
                string cmd = hz.ToString() + "," + hv.ToString();
                geocom.Make_Postion(cmd);
                string str;
                try
                {
                    str = geocom.Measure_Distance_Angle();
                }
                catch
                {
                    continue;
                }
                if (str == "0")
                {
                    parase("无法观测 " + pts.Points[i].Name + "\r\n");
                    continue;
                }
                string[] v = str.Split(',');
                pts.Points[i].Hv = Convert.ToDouble(v[1]);
                pts.Points[i].SlopeDist = Convert.ToDouble(v[2]);
                parase("已测 " + pts.Points[i].Name + "\r\n");
            }
            int index = listpts.Items.IndexOf(section.SectNo);
            if (index == -1)
            {
                return;
            }
            listpts.Items[index] = section.SectNo + "(已测)";
            parase("测量完成\r\n");
            listpts.Refresh();
        }
        //入库
        private void btnsv_Click(object sender, EventArgs e)
        {
            DialogResult re = MessageBox.Show("是否存入数据库?", "询问", MessageBoxButtons.YesNo, MessageBoxIcon.Question
                , MessageBoxDefaultButton.Button1);
            if (re == DialogResult.No)
            {
                return;
            }
            double v = Convert.ToDouble(txtheight.Text);
            tunnelSection section = new tunnelSection();
            section.SectPnts = pts;
            section.ButtomCenter = new TSPCoor(v, 0);
            pts.CalculateCoor(section.ButtomCenter);//计算坐标
            //section.CalButtomCenter2();
            section.SectNo = lbpoint.Text;

            string sql;
            sql = "delete from [result] where [prjid]=" + curprj + " and [name]='" +
            section.SectNo + "' and [no]="+curno;
            m_db.ExecuteSQL(sql);
            sql = "delete from [record] where [prjid]=" + curprj + " and [name]='" +
          section.SectNo + "' and [no]="+curno;
            m_db.ExecuteSQL(sql);
            sql="select [cx],[cy],[r] from [config] where [prjid]="+curprj+" and [name]='"
                + section.SectNo + "'";
            DataTable dt = m_db.GetDataSet(sql).Tables[0];
            double cx = Convert.ToDouble(dt.Rows[0][0]); double cy = Convert.ToDouble(dt.Rows[0][1]); double r = Convert.ToDouble(dt.Rows[0][2]);
            for (int i = 0; i < pts.Points.Count; i++)
            {
                double dv = pts.Points[i].Coor.Coor_V - cy;
                double dh = pts.Points[i].Coor.Coor_H - cx;
                double val = Math.Sqrt(dv * dv + dh * dh) - r;
                val = Math.Round(val, 6);
                sql = "insert into [result] values(" + curprj + ",'" + section.SectNo + "'," + pts.Points[i].Name
                    + "," + val + "," + curno + ")";
                m_db.ExecuteSQL(sql);
                sql = "insert into [record] values(" + curprj + ",'" + section.SectNo + "'," + pts.Points[i].Name
                    + "," + pts.Points[i].Coor.Coor_H + "," + pts.Points[i].Coor.Coor_V + "," + v + "," + curno + ")";
                m_db.ExecuteSQL(sql);
            }
            txtdata.Text = "";
            txtheight.Text = "";
            lbpoint.Text = "";
            MessageBox.Show("入库成功!");
        }
        void parase(string txt)
        {
            txtdata.Text += txt;
            txtdata.SelectionStart = txtdata.Text.Length;
            txtdata.ScrollToCaret();
        }

        void parase1(string txt)
        {
            data.Text += txt;
            data.SelectionStart = data.Text.Length;
            data.ScrollToCaret();
        }
        #endregion


        //结束程序
        private void Mfrm_Closed(object sender, EventArgs e)
        {
            if (geocom != null)
            {
                geocom.port.Close();
            }
        }
        //导出首簿
        private void ExportAllOriginFiles()
        {
            if (curno == -1)
            {
                MessageBox.Show("没有数据!请建立期数!");
                return;
            }
            string sql;
            string name = treeView1.SelectedNode.Text;

            string path = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase.ToString());
            DirectoryInfo direinfo = new DirectoryInfo(path + "\\导出\\" + name + "工程-第" + curno + "期原始首簿");
            if (direinfo.Exists == false)
            {
                direinfo.Create();
            }
            sql = "select [name] from [record] where [prjid]=" + curprj + "and [no]=" + curno + " group by [name] order by [name]";
            DataTable nametb = m_db.GetDataSet(sql).Tables[0];
            for (int i = 0; i < nametb.Rows.Count; i++)
            {
                string ptname = nametb.Rows[i][0].ToString();
                using (StreamWriter w = new StreamWriter(direinfo.FullName +
                              "\\" + ptname + ".txt", false, Encoding.Unicode))
                {
                    sql = "select * from [record] where [prjid]=" + curprj + "and [no]=" + curno + " and [name]='"
                      + ptname + "' order by [point]";
                    DataTable tt = m_db.GetDataSet(sql).Tables[0];
                    for (int j = 0; j < tt.Rows.Count; j++)
                    {
                        //0T,125.2919,2.307,S03,0.0001,0.0000,0.0000,1.443
                        SectionPoint pt = new SectionPoint();
                        pt.Coor = new TSPCoor(Convert.ToDouble(tt.Rows[j]["y"]), Convert.ToDouble(tt.Rows[j]["x"]));
                        SectionPoint ct = new SectionPoint();
                        ct.Coor = new TSPCoor(Convert.ToDouble(tt.Rows[j]["h"]), 0);
                        SvVector sv = new SvVector(ct.Coor, pt.Coor);
                        string row = string.Format("{0},{1},{2},{3},0.0000,0.0000,0.0000,{4}",
                            new object[] { tt.Rows[j]["point"].ToString(), SvAngle.RadToDms(sv.Azimuth).ToString(), Math.Round(sv.Distance, 4), ptname, Math.Round(ct.Coor.Coor_V, 4).ToString() });
                        //string str = (j + 1).ToString() + " 0 " + SvAngle.RadToDms(sv.Azimuth).ToString() + " "
                        //    + Math.Round(sv.Distance, 4) + " " + Math.Round(ct.Coor.Coor_V, 4).ToString();
                        w.WriteLine(row);
                    }
                    w.WriteLine("");
                }
            }
            MessageBox.Show("导出成功!");

        }


        private void output_org_Click(object sender, EventArgs e)
        {
            ExportAllOriginFiles();
        }
        //把弧度化成角度string
        string convrt_rag(double rag)
        {
            double d, m, s;
            rag = (rag / 3.1415916) * 180;
            d = Math.Floor(rag);
            rag = (rag - d) * 60;
            m = Math.Floor(rag);
            s = Math.Round((rag - m) * 60, 2);
            return d.ToString() + "." + m.ToString("00") + (s).ToString("00");
        }




        #region 第一次测量
        //测量仪器高
        private void button2_Click(object sender, EventArgs e)
        {
            if (geocom == null)
            {
                MessageBox.Show("未连接仪器,请先连接!");
                return;
            }
            try
            {
                string str = geocom.Measure_Distance_Angle();
                if (!str.Equals("0"))
                {
                    string[] v = str.Split(',');
                    double hv = Convert.ToDouble(v[1]);
                    if (hv > 3.1415926)
                    {
                        MessageBox.Show("请在盘左\r\n测量仪器高");
                        return;
                    }
                    SectionPoint pptt = new SectionPoint("", v[1], v[2]);
                    pptt.CalculateCoor(new TSPCoor(0, 0));
                    //svpoint pt = mytps.PolarToXYZ(Convert.ToDouble(v[0]), Convert.ToDouble(v[1]), Convert.ToDouble(v[2]));
                    textBox1.Text = Math.Round(-pptt.Coor.Coor_V, 4).ToString();
                }
                else
                {
                    MessageBox.Show("添加失败");
                }
            }
            catch
            {
                MessageBox.Show("失败");
            }

        }

        TunnelSectionPoints pts;
        private void nametxt_TextChanged(object sender, EventArgs e)
        {
           
        }
        //元起点,圆终点
        SectionPoint svStart, svEnd;
        //圆起点的hz
        string hzStart = "0";
        /// <summary>
        /// 测量圆起点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            svStart = SurveyOnePt(-999, "圆起点");
            if (svStart.Hv > Math.PI)
            {
                MessageBox.Show("请在正镜下测量圆起点!");
                svStart = null;
            }
        }
        /// <summary>
        /// 测量圆终点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            svEnd = SurveyOnePt(-999, "圆终点");
        }

        private void sv_btn_Click(object sender, EventArgs e)
        {
            
            if (textBox1.Text == string.Empty)
            {
                MessageBox.Show("仪器高?");
                return;
            }
            if (geocom == null)
            {
                MessageBox.Show("蓝牙?");
                return;
            }
            if (curno > 0)
            {
                MessageBox.Show("期数必须为0");
                return;
            }

            double step = 0;
            try
            {
                step = Convert.ToDouble(textBox2.Text);
            }
            catch
            {
                MessageBox.Show("步长填写错误!");
                return;
            }
            //重新定向为0;

           
            string cmd = hzStart + "," + svStart.Hv.ToString();
            geocom.Make_Postion(cmd);
            geocom.Set_Orientaion();
            step = step / 275.0f;
         

            pts = new TunnelSectionPoints();
            int i = 0;
           
            double hv = svStart.Hv + 2 * Math.PI;
            do
            {
                SectionPoint temp = null;
                string pt_name = string.Format("第{0}点", i + 1);
                temp = SurveyOnePt(hv, pt_name);
                pts.Points.Add(temp);
                //END
                i++;
                hv = hv - step;
            } while (hv > svEnd.Hv);
            pts.Points.Add(SurveyOnePt(svEnd.Hv, string.Format("第{0}点", i + 1)));


            parase1("自动测量已完成,请补点..\r\n");
            //测缝的点
            Fcount = 0;
          
        }
        /// <summary>
        /// 补点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button5_Click(object sender, EventArgs e)
        {
            string pt_name = string.Format("第{0}点", pts.Points.Count + 1);
            pts.Points.Add(SurveyOnePt(-999,pt_name));
        }
        //测缝
        int Fcount = 0;
        private void button6_Click(object sender, EventArgs e)
        {
            string str;
            str = string.Format("开始观测{0}.....\r\n", "接缝点");
            parase1(str);
            try
            {
                str = geocom.Measure_Distance_Angle();
            }
            catch
            {
                str = "接缝点观测失败\r\n";
                parase1(str);
                return ;
            }
            string[] v = str.Split(',');
            Fcount++;
            string pt_no = "F" + Fcount.ToString();
            SectionPoint point = new SectionPoint(pt_no, (v[1]), (v[2]));
            str = string.Format("已完成{0}观测\r\n", pt_no);
            parase1(str);
            pts.Points.Add(point);

        }
        private SectionPoint SurveyOnePt(double dv,string pt_name)
        {
            string str;

            str = string.Format("开始观测{0}.....\r\n", pt_name);
            parase1(str);
            if (dv > -100)
            {
                string cmd = "0," + dv.ToString();
                geocom.Make_Postion(cmd);
            }
            try
            {
                str = geocom.Measure_Distance_Angle();
            }
            catch
            {
                str = pt_name + "观测失败\r\n";
                parase1(str);
                return null;
            }
            if (str == "0")
            {
                str = pt_name + "观测失败\r\n";
                parase1(str);
                return null;
            }
            string[] v = str.Split(',');
            string pt_no = "1";
            //记录圆起点
            if (pt_name == "圆起点")
            {
                hzStart = v[0];
            }
            else if (pt_name == "圆终点")
            {
                pt_no = "2";
            }
            else
            {
                pt_no = (pts.Points.Count + 1).ToString();
            }
            SectionPoint point = new SectionPoint(pt_no, (v[1]), (v[2]));
            str = string.Format("已完成{0}观测\r\n", pt_name);
            parase1(str);
            return point;
        }


        private void btnsave_Click(object sender, EventArgs e)
        {
            DialogResult re =  MessageBox.Show("是否存入数据库?", "询问", MessageBoxButtons.YesNo, MessageBoxIcon.Question
                , MessageBoxDefaultButton.Button1);
            if (re == DialogResult.No)
            {
               return;
            }
            double v = Convert.ToDouble(textBox1.Text);
            tunnelSection section = new tunnelSection();
            section.SectPnts = pts;
            section.ButtomCenter = new TSPCoor(v, 0);
            pts.CalculateCoor(section.ButtomCenter);//计算坐标
            section.SectNo = nametxt.Text;
            //tunnelArc arc = new tunnelArc();
            //arc.CircleDefineByPoints(ref pts.Points);
            string sql = "delete from [config] where [prjid]=" + curprj + " and [name]='" +
                section.SectNo + "'";
            m_db.ExecuteSQL(sql);
            sql = "insert into [config] values(" + curprj + ",'" + section.SectNo + "'," + "0"
                + "," + "0" + "," + v + "," + "0" + ")";
            m_db.ExecuteSQL(sql);
            //sql = "delete from [result] where [prjid]=" + curprj + " and [name]='" +
            //section.SectNo + "' and [no]="+curno;
            //m_db.ExecuteSQL(sql);
            sql = "delete from [record] where [prjid]=" + curprj + " and [name]='" +
          section.SectNo + "' and [no]=" + curno;
            m_db.ExecuteSQL(sql);
            for (int i = 0; i < pts.Points.Count; i++)
            {

  
                //sql = "insert into [result] values(" + curprj + ",'" + section.SectNo + "','" + pts.Points[i].Name
                //    + "'," + val + "," + curno + ")";
                //m_db.ExecuteSQL(sql);
                sql = "insert into [record] values(" + curprj + ",'" + section.SectNo + "','" + pts.Points[i].Name
                    + "'," + pts.Points[i].Coor.Coor_H + "," + pts.Points[i].Coor.Coor_V + "," + v + "," + curno + ")";
                m_db.ExecuteSQL(sql);
            }
            data.Text = "";
            textBox1.Text = "";
            nametxt.Text = "";
            MessageBox.Show("入库成功!");
        }
        #endregion

        private void list_result_SelectedIndexChanged(object sender, EventArgs e)
        {
            string name = list_result.Items[list_result.SelectedIndex].ToString();
            string sql;
            if (curno > 0)
            {
                sql = "select [point] as [序号],round(([val]-[v])*1000,1) as [本次变化],round([val]*1000,1) as [累积变化] from [result] "+
                    "cross join (select [val] as [v],[point] as [p],[prjid] as [pj],[name] as [n],[no] as [nn] from [result]) as tb"+
                    " where [point]=[p] and [prjid]=[pj] and [name]=[n] and [prjid]="+curprj+" and [name]='"+name+"'"
                    +" and [no]="+curno+" and [nn]="+(curno-1).ToString()+" order by [point]";
                DataTable dt = m_db.GetDataSet(sql).Tables[0];
                dataGrid1.DataSource = dt;
            }
            else
            {
                sql = "select [point] as [序号],round([val]*1000,1) as [本次变化],round([val]*1000,1) as [累积变化] from [result] where [prjid]=" + curprj + " and [name]='" +
                                     name + "' and [no]=" + (curno).ToString() + " order by [point]";
                DataTable dt = m_db.GetDataSet(sql).Tables[0];
                dataGrid1.DataSource = dt;
            }

        }

        private void tabcontrol_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabcontrol.SelectedIndex == 4)
            {
                load_reuslt_pts();
            }
        }



  




  

  

    
 


  

















    }
}